package cn.team11.sds.dayi.debugpage;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import cn.team11.sds.dayi.ConfigHelper;
import cn.team11.sds.dayi.R;
import cn.team11.sds.dayi.ble.BLEDiscoveryActivity;
import cn.team11.sds.dayi.envconfig.ConfigEnvActivity;
import cn.team11.sds.dayi.qrcode.QRCodeHelper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.AlinkSDK;
import com.aliyun.alink.alirn.dev.BoneDevHelper;
import com.aliyun.alink.business.alink.ALinkBusiness;
import com.aliyun.alink.business.alink.ALinkConstant;
import com.aliyun.alink.business.downstream.DeviceBusiness;
import com.aliyun.alink.business.helper.ChannelBindHelper;
import com.aliyun.alink.business.login.AlinkLoginBusiness;
import com.aliyun.alink.business.login.IAlinkLoginCallback;
import com.aliyun.alink.page.pageroutor.ARouter;
import com.aliyun.alink.page.rn.RNActivity;
import com.aliyun.alink.sdk.net.anet.api.persistentnet.IOnPushListener;
import com.aliyun.alink.utils.ALog;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.imnjh.imagepicker.SImagePicker;
import com.imnjh.imagepicker.activity.PhotoPickerActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Pattern;

import cn.team11.sdsPackager.T11PackageConfig;
import cn.team11.sdsPackager.TestPackageConfig_test;
import cn.team11.util.ImageUtil;
import cn.team11.util.T11Log;
import cn.team11.util.T11NdkLib;
import cn.team11.util.imagePicker.SingleFileLimitInterceptor;
import cn.team11.util.update.T11UpdateService;
import okhttp3.Call;
import okhttp3.Callback;

public class DebugActivity extends Activity {

    private static final String TAG = "DebugActivity";

    private ListView listView;
    private JSONArray listJson = null;
    private JSONObject configJson = null;
    private DeviceBusiness deviceBiz = null;
    private Button buttonReload = null;
    public static final int REQUEST_CODE_IMAGE = 101;
    private RequestQueue requestQueue = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_debug);

        initView();
        T11Log.d("ndk test ========"+T11NdkLib.strFromNdk());
        loadListData();

        initPushTunnel();
        T11UpdateService.startVersionCheck(this);

    }


    private void initPushTunnel() {
        deviceBiz = new DeviceBusiness();
        deviceBiz.startWatching(DeviceBusiness.FEATURE_DOWNSTREAM_WATCHER);
        deviceBiz.setDownstreamListener(new IOnPushListener() {
            @Override
            public void onCommand(String s) {
                Toast.makeText(DebugActivity.this, "收到下推数据", Toast.LENGTH_SHORT).show();
                T11Log.d("收到下推数据：" + s);
            }

            @Override
            public boolean filter(String s) {
                return true;
            }
        }, true);
    }

    private void initView() {
        this.buttonReload = (Button) findViewById(R.id.button_reload);

        this.listView = (ListView) findViewById(R.id.bone_listview);
        this.listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String url = listJson.getJSONObject(position).getString("url");
                if (TextUtils.isEmpty(url)) {
                    Toast.makeText(DebugActivity.this, "配置URL为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                ALog.d(TAG, "url = " + url);
                ARouter.navigate(DebugActivity.this, url);
            }
        });
    }

    // Btn Onclick Action

    public void envSwitch(View view) {
        Intent intent = new Intent(this, ConfigEnvActivity.class);
        startActivity(intent);
    }

    public void accountLogin(View view) {
        if (AlinkLoginBusiness.getInstance().isLogin()) {
            Toast.makeText(this, "账号已登录", Toast.LENGTH_SHORT).show();
        } else {
            AlinkLoginBusiness.getInstance().login(this, null);
        }
    }

    public void accountLogout(View view) {
        if (!AlinkLoginBusiness.getInstance().isLogin()) {
            Toast.makeText(this, "账号未登录", Toast.LENGTH_SHORT).show();
            return;
        }

        AlinkLoginBusiness.getInstance().logout(this, new IAlinkLoginCallback() {
            @Override
            public void onSuccess() {
                Toast.makeText(DebugActivity.this, "账号登出成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int i, String s) {
                Toast.makeText(DebugActivity.this, "账号登出失败," + s, Toast.LENGTH_SHORT).show();
            }
        });

    }

    public void wifiDeviceConfig(View view) {
        if (configJson == null || TextUtils.isEmpty(configJson.getString("deviceConfigURL"))) {
            Toast.makeText(this, "配置获取失败或配置URL为空", Toast.LENGTH_SHORT).show();
            return;
        }
        String url = configJson.getString("deviceConfigURL");
        ARouter.navigate(DebugActivity.this, url);
    }

    public void bleDeviceDiscovery(View view) {
        Intent intent = new Intent(this, BLEDiscoveryActivity.class);
        startActivity(intent);
    }

    public void boneDebug(View view) {
        final EditText editText = new EditText(this);

        new ConfigHelper().loadFromDisk(this);

        editText.setText(ConfigHelper.ip);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请输入DevSever的IP:")
                .setView(editText)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String ip = editText.getText().toString();
                        handleIP(ip);
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        builder.show();
    }

    public void scanDebug(View view) {
        QRCodeHelper.open(this);
    }

    public void loadBone2(View view) {
        T11Log.d("boneUrl = " + T11PackageConfig.boneUrl);
        ARouter.navigate(DebugActivity.this, T11PackageConfig.boneUrl);
    }

    /**
     * 加载大一保险柜bone
     *
     * @param view
     */
    public void testBone(View view) {
        T11Log.d("boneURL = " + TestPackageConfig_test.boueUrl);
        ARouter.navigate(DebugActivity.this, TestPackageConfig_test.boueUrl);
    }

    /**
     * 获取用户信息
     *
     * @param view
     */
    public void getUserID(View view) {
        try {
            if (AlinkLoginBusiness.getInstance().isLogin()) {
                String userID = AlinkLoginBusiness.getInstance().getUserID();
                T11Log.e(userID);
            }
        } catch (Exception e) {
            T11Log.e(e.toString());
        }
    }

    public void selectImage(View view) {
        SImagePicker
                .from(DebugActivity.this)
                .maxCount(1)
                .rowCount(3)
                .showCamera(true)
                .pickMode(SImagePicker.MODE_IMAGE)
                .fileInterceptor(new SingleFileLimitInterceptor())
                .forResult(REQUEST_CODE_IMAGE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        T11Log.d("--------------------------------");
        switch (requestCode) {
            case REQUEST_CODE_IMAGE:
                T11Log.d("--------");
                if (resultCode == Activity.RESULT_OK) {
                    final ArrayList<String> pathList =
                            data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);
                    final boolean original =
                            data.getBooleanExtra(PhotoPickerActivity.EXTRA_RESULT_ORIGINAL, false);
//            pickAdapter.setNewData(pathList);
                    try {
                        T11Log.d("pathList = " + pathList);
                        ImageUtil.uploadImg("http://192.168.0.110/t11_gaokemei/uploadFile?fname=" + "liyuanupload.png", pathList.get(0), "liyuanupload.png", new Callback() {

                            @Override
                            public void onFailure(Call call, IOException e) {
                                T11Log.d("图片上传失败");
                            }

                            @Override
                            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                                T11Log.d("图片上传成功");
                            }
                        }, this);
                    } catch (IOException e) {
                        T11Log.e(e);
                    }
                }
                break;
            default:
                QRCodeHelper.onActivityResult(this, requestCode, resultCode, data);
        }
    }

    private void handleIP(String ip) {

        // check ip
        boolean match = Pattern.matches("((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))", ip);

        if (!match) {
            Toast.makeText(this, "无效的IP地址", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!TextUtils.equals(ip, ConfigHelper.ip)) {
            ConfigHelper.ip = ip;
            new ConfigHelper().saveToDisk(this);
        }

        new BoneDevHelper().getBundleInfoAsync(this, ip, new BoneDevHelper.OnBondBundleInfoGetListener() {
            @Override
            public void onSuccess(BoneDevHelper.BoneBundleInfo boneBundleInfo) {
                if (null == boneBundleInfo) {
                    return;
                }

                if (null == boneBundleInfo.data) {
                    return;
                }

                if (!"200".equalsIgnoreCase(boneBundleInfo.code)) {

                    String message = boneBundleInfo.data.get("message");
                    Toast.makeText(DebugActivity.this, message, Toast.LENGTH_SHORT).show();

                    return;
                }

                String url = boneBundleInfo.data.get("url");
                String config = boneBundleInfo.data.get("config");
                String params = boneBundleInfo.data.get("params");

                url = url.replaceFirst("http://", "react://");

                Intent intent = new Intent(DebugActivity.this, RNActivity.class);
                intent.setData(Uri.parse(url));
                intent.putExtra("extraConfig", config);
                intent.putExtra("extraParams", params);

                DebugActivity.this.startActivity(intent);
            }

            @Override
            public void onError(String message, Exception e) {
                Toast.makeText(DebugActivity.this, message, Toast.LENGTH_SHORT).show();

                if (null != e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void reload(View view) {
        loadListData();
    }

    private void loadListData() {

        if (null == this.requestQueue) {
            this.requestQueue = Volley.newRequestQueue(this);
        }

        String url = "http://gaic.alicdn.com/tms/boneDemoConfig.json";

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            configJson = JSON.parseObject(response);
                            listJson = configJson.getJSONArray("boneAppList");
                            listView.setAdapter(new ListViewAdapter(DebugActivity.this, listJson));

                            if (null != buttonReload) {
                                buttonReload.setVisibility(View.GONE);
                            }
                        } catch (Exception e) {
                            ALog.e(TAG, "error = " + e.toString());
                            Toast.makeText(DebugActivity.this, "配置解析失败", Toast.LENGTH_SHORT).show();

                            if (null != buttonReload) {
                                buttonReload.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(DebugActivity.this, "加载配置失败", Toast.LENGTH_SHORT).show();

                if (null != buttonReload) {
                    buttonReload.setVisibility(View.VISIBLE);
                }
            }
        });
        this.requestQueue.add(stringRequest);
    }

    //解绑消息通道
    public void unBindMsgChannel() {
        ChannelBindHelper.getInstance().onLoginChanged(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (null != requestQueue) {
            requestQueue.stop();
        }
    }
}
